package com.zqs.compareface.server.local;

import com.zqs.compareface.utils.impl.CreateFFmpegFramegrabberUtil;
import com.zqs.compareface.utils.impl.HumanCheckUtil;
import org.bytedeco.javacv.*;
import org.opencv.core.Core;
import org.opencv.core.Mat;

import javax.swing.*;

/**
 * @Program: FaceCompare
 * @Description:
 * @Author: zqs
 * @Create： 2021-08-11-21:06
 */
public class LocalDetectionBody {
    static {
        // 在使用OpenCV前必须加载Core.NATIVE_LIBRARY_NAME类,否则会报错
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public static void main(String[] args) {
        LocalDetectionBody localDetectionBody = new LocalDetectionBody();
        localDetectionBody.pullAndScanBodyAndShow();
    }

    /**
     * 拉流并检测人体，同时展示
     */
    public void pullAndScanBodyAndShow(){
        //调用FFmpegFrameGrabber创建工具
        FFmpegFrameGrabber grabber = CreateFFmpegFramegrabberUtil.createFFmpegFrameGrabber();
        /**
         * 开一个窗口查看视频画面，根据需要开启
         */
        CanvasFrame canvasFrame = new CanvasFrame("人体检测");
        canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvasFrame.setAlwaysOnTop(true);
        //转换器
        OpenCVFrameConverter.ToOrgOpenCvCoreMat converter = new OpenCVFrameConverter.ToOrgOpenCvCoreMat();
        int index = 0;
        while (grabber != null) {
            try {
                Frame frame = grabber.grabImage();
                Mat mat = converter.convert(frame);
                HumanCheckUtil.pedestrianDetection(mat);
                canvasFrame.showImage(frame);

            } catch (FFmpegFrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }
        CreateFFmpegFramegrabberUtil.closeFFmpegFrameGrabber(grabber);
    }

    /**
     * @param  grabber
     * 拉流并检测人体，不展示
     */
    public void pullAndScanBodyWhitoutShow(){
        //调用FFmpegFrameGrabber创建工具
        FFmpegFrameGrabber grabber = CreateFFmpegFramegrabberUtil.createFFmpegFrameGrabber();
        //转换器
        OpenCVFrameConverter.ToOrgOpenCvCoreMat converter = new OpenCVFrameConverter.ToOrgOpenCvCoreMat();
        //开始抽帧和调用检测方法
        while (grabber != null) {
            try {
                Frame frame = grabber.grabImage();
                Mat mat = converter.convert(frame);
                HumanCheckUtil.pedestrianDetection(mat);
            } catch (FFmpegFrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }
        CreateFFmpegFramegrabberUtil.closeFFmpegFrameGrabber(grabber);
    }
}
